// js/ui/PageManager.js (优化版)
import LoadingAnimation from '../ui/LoadingAnimation.js';
// 导入所有页面类
import LoginPage from '../pages/LoginPage.js';
import HomePage from '../pages/HomePage.js';
import GamePage from '../pages/GamePage.js';
import SettlementPage from '../pages/SettlementPage.js';
import ProfilePage from '../pages/ProfilePage.js';
import LeaderboardPage from '../pages/LeaderboardPage.js';
import PosterPage from '../pages/PosterPage.js'; // <-- 新增导入


import ResourceManager from './ResourceManager.js';
import UserManager from './UserManager.js';

const api = require('../api/index.js');

export default class PageManager {
  constructor(canvas, ctx, screenAdapter) {
    // 单例模式
    if (PageManager.instance) {
      return PageManager.instance;
    }

    this.canvas = canvas;
    this.ctx = ctx;
    this.screenAdapter = screenAdapter;

    // 存储页面类，用于懒加载实例化
    this.pageClasses = new Map();
    // 当前页面实例
    this.currentPage = null;

    // 创建两种加载动画
    this.globalLoading = new LoadingAnimation(this.canvas, this.ctx, this.screenAdapter, 'global');
    this.pageLoading = new LoadingAnimation(this.canvas, this.ctx, this.screenAdapter, 'page');

    // 加载状态
    this.isLoadingResources = false;
    this.isSwitchingPage = false; // 页面切换锁

    // 初始化管理器
    this.resourceManager = new ResourceManager();
    this.userManager = new UserManager(api);

    // 注册页面类并初始化全局事件
    this._registerPages();
    this._initGlobalTouchHandlers();

    PageManager.instance = this;
  }

  /**
   * 注册所有页面类
   */
  _registerPages() {
    this.pageClasses.set('login', LoginPage);
    this.pageClasses.set('home', HomePage);
    this.pageClasses.set('game', GamePage);
    this.pageClasses.set('settlement', SettlementPage);
    this.pageClasses.set('profile', ProfilePage);
    this.pageClasses.set('leaderboard', LeaderboardPage);
    this.pageClasses.set('poster', PosterPage);
  }

  /**
   * 初始化全局触摸事件处理（中央调度模式）
   */
  _initGlobalTouchHandlers() {
    wx.onTouchStart(this._handleGlobalTouchStart.bind(this));
    wx.onTouchMove(this._handleGlobalTouchMove.bind(this));
    wx.onTouchEnd(this._handleGlobalTouchEnd.bind(this));
    wx.onTouchCancel(this._handleGlobalTouchCancel.bind(this));
  }

  /**
   * 全局触摸事件处理器 - 将事件分发给当前页面
   */
  _handleGlobalTouchStart(event) {
    // 【关键】如果正在切换页面或加载资源，则忽略事件
    if (this.isSwitchingPage || this.isLoadingResources) return;
    if (this.currentPage && this.currentPage.handleTouchStart) {
      this.currentPage.handleTouchStart(event);
    }
  }

  _handleGlobalTouchMove(event) {
    if (this.isSwitchingPage || this.isLoadingResources) return;
    if (this.currentPage && this.currentPage.handleTouchMove) {
      this.currentPage.handleTouchMove(event);
    }
  }

  _handleGlobalTouchEnd(event) {
    if (this.isSwitchingPage || this.isLoadingResources) return;
    if (this.currentPage && this.currentPage.handleTouchEnd) {
      this.currentPage.handleTouchEnd(event);
    }
  }

  _handleGlobalTouchCancel(event) {
    if (this.isSwitchingPage || this.isLoadingResources) return;
    if (this.currentPage && this.currentPage.handleTouchCancel) {
      this.currentPage.handleTouchCancel(event);
    }
  }

  /**
   * 启动游戏
   */
  async start() {
    this.globalLoading.start();
    this.isLoadingResources = true;

    this.resourceManager.setProgressCallback((progress) => {
      this.globalLoading.setProgress(progress);
    });

    const loginSuccess = await this.userManager.login();
    if (!loginSuccess) {
      // 可以处理登录失败逻辑，比如显示提示
    }

    await this.resourceManager.loadAllResources();
    await new Promise(resolve => setTimeout(resolve, 500)); // 稍作延迟，让用户看到100%

    this.globalLoading.stop();
    this.isLoadingResources = false;

    await this.showPage('login');
    //await this.showPage('statistics');
  }

  /**
   * 【核心方法】切换到指定页面
   * @param {string} pageName 要切换到的页面名称
   * @param {...any} args 传递给目标页面的参数
   */
  async showPage(pageName, ...args) {
    if (this.isSwitchingPage) {
      console.warn(`[PageManager] Already switching pages, ignoring request for "${pageName}".`);
      return;
    }

    const PageClass = this.pageClasses.get(pageName);
    if (!PageClass) {
      const availablePages = Array.from(this.pageClasses.keys()).join(', ');
      console.error(`[PageManager] Error: Page "${pageName}" not found. Available pages: ${availablePages}`);
      return;
    }

    // 【关键】设置切换锁，防止在切换过程中响应触摸
    this.isSwitchingPage = true;
    this.pageLoading.start();

    // 1. 退出当前页面
    if (this.currentPage) {
      if (typeof this.currentPage.onExit === 'function') {
        this.currentPage.onExit();
      }
    }

    // 2. 创建并初始化新页面
    let newPage = null;
    try {
      // 3. 【新增】预加载页面资源
      await this.resourceManager.preloadPageResources(pageName);

      newPage = new PageClass(
        this.canvas, this.ctx, this, this.resourceManager, this.screenAdapter, api, this.userManager
      );
      await newPage.initialize(...args);

      // 5. 设置页面切换完成后的淡出回调
      this.pageLoading.setFadeOutCallback(() => {
        // 淡出完成后才设置新页面为当前页面
        this.currentPage = newPage;
        newPage.onEnter(...args);
        this.isSwitchingPage = false;
        console.log(`[PageManager] Page "${pageName}" switched successfully.`);
      });
      // 6. 开始淡出加载动画
      this.pageLoading.stop();
    } catch (error) {
      console.error(`[PageManager] Error initializing page "${pageName}":`, error);
      this.pageLoading.stop();
      this.isSwitchingPage = false;
      // 可以考虑回退到上一个页面或显示错误页面
      this.currentPage = null;
      return;
    }

    // 3. 切换到新页面
    this.currentPage = newPage;
    if (typeof this.currentPage.onEnter === 'function') {
      this.currentPage.onEnter(...args);
    }

    this.pageLoading.stop();
    this.isSwitchingPage = false;
    console.log(`[PageManager] Successfully switched to page: "${pageName}".`);
  }

  /**
   * 更新游戏逻辑
   */
  update(dt) {
    // 1. 更新全局资源加载动画
    if (this.isLoadingResources) {
      this.globalLoading.update(dt);
    }

    // 2. 更新页面切换加载动画
    if (this.isSwitchingPage) {
      this.pageLoading.update(dt);
    }

    // 3. 更新当前页面
    if (this.currentPage && !this.isSwitchingPage && this.currentPage.update) {
      this.currentPage.update(dt);
    }
  }

  /**
   * 渲染游戏画面
   */
  render() {
    const ctx = this.ctx;
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    ctx.save();
    // 屏幕适配变换
    ctx.translate(this.screenAdapter.offsetX * this.screenAdapter.pixelRatio, this.screenAdapter.offsetY * this.screenAdapter.pixelRatio);
    ctx.scale(this.screenAdapter.scale * this.screenAdapter.pixelRatio, this.screenAdapter.scale * this.screenAdapter.pixelRatio);

    if (this.isLoadingResources) {
      this.globalLoading.render();
    } else if (this.isSwitchingPage) {
      this.pageLoading.render();
    } else if (this.currentPage) {
      this.currentPage.render();
    }

    ctx.restore();
  }

  /**
   * 获取当前页面
   */
  getCurrentPage() {
    return this.currentPage;
  }
}
